package com.guiji.text2video.job.task;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RuntimeUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.http.HtmlUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import com.guiji.text2video.job.domain.NewsSimplePushVO;
import com.guiji.text2video.job.domain.SpiderNewsStat;
import com.guiji.text2video.job.domain.Text2videoJob;
import com.guiji.text2video.job.mapper.Text2videoJobMapper;
import com.guiji.text2video.job.util.DingUtil;
import org.junit.platform.commons.util.RuntimeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Copyright (C), 2018-2021
 * @FileName: PushNewsKeJiTimingTask
 * @Author: scl
 * @Date: 2021/8/30 15:44
 * @Description: 拆分定时任务
 * 1,在55上存储。
 * 2,推送只考虑55节点。
 * 3,54节点合成成品视频。
 */
@Component("in")
public class PushNginxVideo {

    private static final Logger logger = LoggerFactory.getLogger(PushNginxVideo.class);

    @Autowired(required = false)
    Text2videoJobMapper jobMapper;

    @Autowired
    PushTask pushTask;

    /**
     * @descp:
     * @param:
     * @Author: scl
     * @Date: 2022/1/11 15:18
     */
    public void h(String direction, String channel, String cookieName, Integer num) {
        logger.info("视频直接上传-每次推送数量:{},使用目录:{}", num, direction);
        String url = "http://172.16.101.135/kuai_video_all/prod/" + direction + "/";
        String path = "/home/yaoao/kuai_video_all/prod/" + direction + "/";
        HttpResponse response = HttpRequest.get(url).execute();
        String resp = response.body();
        String pattern = "Job.*?Job.*?\\.";
        Pattern p = Pattern.compile(pattern);
        Matcher m = p.matcher(resp);
        int a = 1;
        while (m.find()) {
            String lineUrl = m.group();
            String pattern1 = "Job.*?mp4";
            Pattern p1 = Pattern.compile(pattern1);
            Matcher m1 = p1.matcher(lineUrl);
            while (m1.find()) {
                lineUrl = URLUtil.decode(url + m1.group());
            }
            String title = lineUrl.replaceAll("http.*?Job-.*?-.*?-.*?-", "").replaceAll(".mp4", "");
            String savePath = lineUrl.replace("http://172.16.101.135/", "/home/yaoao/");
            //savePath包涵空格，实现空格替换
            savePath = savePath.replace(" ", "\\ ");
            String mvCmd = "sshpass -p 123 ssh  -o StrictHostKeyChecking=no yaoao@172.16.101.135 ";
            mvCmd = mvCmd + "mv \'" + savePath + "\' " + path + "pushed/";
            logger.info("执行命令:{}", mvCmd);
            pushVideo(lineUrl, channel, title, cookieName, mvCmd);
            a = a + 1;
            if (num + 1 == a) {
                break;
            }
        }
    }

    /**
     * @descp: 1, 直接推送。
     * @param: 2，记录推送结果。
     * in.p()
     * 'meishi-jxdmsj','家常美味','meishi',3
     * 'zhongdong','中东的历史与故事','woaikanxinwen',3
     * 'yejy-scp','家庭教育Family Education','yuer',3
     * 'kjdbh-scp','前沿科技','kejitanzhang',3
     * 'delzs-scp','冷知识','lengzhishi',3
     * 'sslzs-scp','懂点啥','kepu',3
     * <p>
     * in.p('sslzs-scp','懂点啥','kepu',3)
     * <p>
     * /data/hdd/douyin/meishi-hthbf	抖音	海獭烘焙坊
     * /data/hdd/douyin/meishi-lrmsys	抖音	老阮美食艺术
     * /data/hdd/douyin/meishi-xcdll	抖音	晓婵的料理
     * /data/hdd/douyin/dxshprj       抖音     丁先生烘焙日记
     * @Author: scl
     * @Date: 2021/11/4 17:15
     */
    public void p(String direction, String channel, String cookieName, Integer num) {
        logger.info("视频直接上传-每次推送数量:{},使用目录:{}", num, direction);

        SpiderNewsStat stat = new SpiderNewsStat();
        stat.setNewsCategory(channel);
        List list = pushTask.getSpiderNewsStat(stat);

        String url = "http://172.16.160.55/douyin/" + direction + "/";
        String path = "/data/hdd/douyin/" + direction + "/";
        HttpResponse response = HttpRequest.get(url).execute();
        String resp = response.body();
        resp = HtmlUtil.cleanHtmlTag(resp);
        String lines[] = resp.split("\\r?\\n");
        logger.info("视频共有:{}", lines.length - 4);
        int count = 0;
        for (String line : lines) {
            if (line.contains(".mp4")) {

                if (count == num) {
                    return;
                }

                String chineseName = line.split(".mp4")[0];
                chineseName = URLUtil.decode(chineseName);
                String lineUrl = URLUtil.decode(url + chineseName + ".mp4");

                String mvCmd = "sshpass -p Guiji2021go! ssh  -o StrictHostKeyChecking=no root@172.16.160.55 ";
                mvCmd = mvCmd + "mv " + path + chineseName + ".mp4 " + path + "pushed/";

                duplication(list, lineUrl, channel, chineseName, cookieName, mvCmd);
                count++;
            }
        }


    }


    private void duplication(List<SpiderNewsStat> list, String lineUrl, String channel, String fileName, String cookieName, String mvCmd) {
        for (SpiderNewsStat stat : list) {
            if (stat.getBackup2().equals(fileName)) {
                //终止方法
                return;
            }
        }
        pushVideo(lineUrl, channel, fileName, cookieName, mvCmd);
    }

    private void pushVideo(String url, String channel, String title, String cookieName, String mvCmd) {
        if (cookieName.contains("asianbusinessnews")) {
            title = "【叨叨哥聊封神】" + title;
        }
        //下载文件secondCreation
        String secondName = IdUtil.simpleUUID() + ".mp4";
        String wgetCmd = "wget " + URLUtil.encode(url) + " -O /data/hdd/" + secondName;
        RuntimeUtil.execForStr(wgetCmd);

        //传输文件
        String saveFile = "/data/hdd/" + secondName;
        long fileSizeBytes = new File(saveFile).length();
        String scpCmd = "scp -i /data/text2video/duix.pem  " + saveFile + " centos@44.236.176.10:/home/centos/news_video";
        RuntimeUtil.execForStr(scpCmd);

        //删除缓存文件
        RuntimeUtil.execForStr("rm -f " + saveFile);

        NewsSimplePushVO nspVO = new NewsSimplePushVO();
        //修改路径
        nspVO.setPath("/home/centos/news_video/" + secondName);
        if (title.length() > 100) {
            title = title.substring(0, 99);
        }
        nspVO.setTitle(title);
        nspVO.setDescription(title);
        nspVO.setChannel(channel);
        nspVO.setUsername(cookieName);
        nspVO.setTimeout(pushTask.getTimeoutSecond(fileSizeBytes));

        //开始推送
        HttpResponse httpResponse = null;
        logger.info("发起推送请求,对象:{}", JSONUtil.parseObj(nspVO).toString());
        try {
            httpResponse = HttpRequest.post("http://44.236.176.10:5556/api/upload").timeout(7200000).body(JSONUtil.parseObj(nspVO).toString()).executeAsync();
        } catch (Exception e) {
            logger.info("http请求异常:{}", e.toString());
        }

        Text2videoJob videoJob = new Text2videoJob();
        videoJob.setBackupText(nspVO.getChannel());
        videoJob.setTitle(nspVO.getTitle());
        videoJob.setJobId(nspVO.getUsername());
        if (ObjectUtil.isNotEmpty(httpResponse) && httpResponse.getStatus() == 200) {
            logger.info("推送成功:{}", JSONUtil.parseObj(nspVO).toString());
            pushTask.InsertStatSpider(videoJob, 0, httpResponse);
            mv(mvCmd);
        } else {
            pushTask.InsertStatSpider(videoJob, 1, httpResponse);
            if (ObjectUtil.isNotEmpty(httpResponse) && httpResponse.getStatus() == 505) {
                logger.info("505状态验证本人操作:{}", nspVO.getUsername());
                DingUtil.sendMsg("!!! 监控到当前youtube账号验证本人操作", nspVO.getUsername());
                return;
            } else if (ObjectUtil.isNotEmpty(httpResponse) && httpResponse.getStatus() == 504) {
                logger.info("504状态已达到每日上传数上限:{},保留视频:{}", nspVO.getUsername(), JSONUtil.parseObj(nspVO).toString());
                return;
            } else if (ObjectUtil.isNotEmpty(httpResponse) && httpResponse.getStatus() == 503) {
                logger.info("503状态并发上限，保留视频：{}", JSONUtil.parseObj(nspVO).toString());
                return;
            } else if (ObjectUtil.isNotEmpty(httpResponse) && httpResponse.getStatus() == 502) {
                logger.info("502状态当前账号cookie过期:{}", nspVO.getUsername());
                DingUtil.sendMsg("急需处理 监控到当前youtube账号cookie过期", nspVO.getUsername());
                return;
            } else if (ObjectUtil.isNotEmpty(httpResponse) && httpResponse.getStatus() == 501) {
                logger.info("501状态当前视频在草稿箱，不需要尝试推送");
                mv(mvCmd);
            } else {
                mv(mvCmd);
                logger.info("500错误需要删除，频道:{},使用jobId:{},视屏标题:{}", channel, videoJob.getJobId(), videoJob.getTitle());
            }
        }
    }

    private void mv(String mvCmd) {
        //将文件移动到pushed目录
        logger.info("移动视频：{}", mvCmd);
        //Linux命令写法   .sh文件之后可以再加命令getModuleList
        String[] command = {"/bin/sh", "-c", mvCmd};
        try {
            Runtime.getRuntime().exec(command);
        } catch (IOException e) {
            logger.info("移动视频mvCmd执行异常");
            e.printStackTrace();
        }
    }

}